from django.conf import settings
from django.db import models
from apps.system.models import Upload
from utils.exceptions import CustomError


class Article(models.Model):
    title = models.CharField(verbose_name='标题', max_length=200)
    describe = models.CharField(verbose_name='描述', max_length=200)
    thumbnail = models.ForeignKey(Upload, verbose_name='缩略图', on_delete=models.PROTECT, null=True, blank=True)
    content = models.TextField(verbose_name='内容')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='作者', on_delete=models.PROTECT, blank=True)
    tags = models.CharField(verbose_name='标签', max_length=50, help_text='多个标签请用|隔开', null=True)
    brown_count = models.IntegerField(verbose_name='浏览量', default=0)
    like_count = models.IntegerField(verbose_name='点赞量', default=0)
    collect_count = models.IntegerField(verbose_name='收藏量', default=0)
    status = models.BooleanField(verbose_name='状态', default=True)
    is_top = models.BooleanField(verbose_name='置顶', default=False)
    is_hot = models.BooleanField(verbose_name='热门', default=False)
    is_recommend = models.BooleanField(verbose_name='推荐', default=False)
    delete = models.BooleanField(verbose_name='删除', default=False)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)

    class Meta:
        db_table = 'article'
        verbose_name = '文章'
        ordering = ['-create_time']
        default_permissions = ()

    @staticmethod
    def get_instance_by_id(id):
        try:
            id = int(id)
        except:
            raise CustomError('无效的id')

        instance = Article.objects.filter(pk=id).first()
        if not instance:
            raise CustomError('未找到对应的实例')
        return instance
